from datetime import datetime, timedelta
from flask import Blueprint, request, jsonify, send_file, g
from app.models.device import Device
from app.models.user import User
from app.models.user_device import UserDevice
from app.models.mongodb import mongodb
from app.models.mysql_db import db # SQLAlchemy instance
from app.utils.logger import get_logger
# from app.utils.decorators import require_json # 如果POST /analyze接口严格要求json
from app.utils.auth import auth_required # 假设所有接口都需要认证
import pandas as pd
import io
from bson import ObjectId # 如果需要处理MongoDB ObjectId

logger = get_logger(__name__)

# 创建蓝图，URL前缀与API文档中的 /device/... 对应
device_bp = Blueprint('device', __name__, url_prefix='/api/device')

# 辅助函数：将字符串日期转换为时间戳
def _parse_date_to_timestamp(date_str, end_of_day=False):
    if not date_str:
        return None
    try:
        dt = datetime.strptime(date_str, '%Y-%m-%d')
        if end_of_day:
            dt = dt.replace(hour=23, minute=59, second=59, microsecond=999999)
        return int(dt.timestamp())
    except ValueError:
        # 尝试解析ISO格式
        try:
            dt = datetime.fromisoformat(date_str.replace('Z', '+00:00'))
            if end_of_day:
                 # 对于ISO格式，如果已经是具体时间，则end_of_day可能不需要特别处理，或者根据需求调整
                dt = dt.replace(hour=23, minute=59, second=59, microsecond=999999)
            return int(dt.timestamp())
        except ValueError:
            return None

# 1. 获取设备状态和用户使用情况数据
@device_bp.route('/status', methods=['GET'])
@auth_required
def get_device_status_and_usage():
    """获取指定用户和设备的状态信息及使用情况"""
    try:
        user_id_param = request.args.get('userId')
        device_id_param = request.args.get('deviceId')
        start_date_str = request.args.get('startDate')
        end_date_str = request.args.get('endDate')

        if not user_id_param:
            return jsonify({'code': 400, 'msg': '缺少必要参数userId', 'data': None}), 400
            
        # 允许查询所有设备
        if device_id_param == 'all' or not device_id_param:
            # 查询用户的所有设备
            user = User.query.filter_by(id=user_id_param).first()
            if not user:
                return jsonify({'code': 404, 'msg': '用户不存在', 'data': None}), 404
                
            # 查询与该用户关联的所有设备
            user_devices = UserDevice.query.filter_by(user_id=user.id).all()
            
            if not user_devices:
                return jsonify({'code': 200, 'msg': '用户没有绑定设备', 'data': {'devices': [], 'total': 0}}), 200
                
            # 获取设备列表
            devices_list = []
            for user_device in user_devices:
                device = Device.query.filter_by(id=user_device.device_id).first()
                if device:
                    latest_data = mongodb.db.environment_data.find_one(
                        {'deviceId': device.device_id},
                        sort=[('timestamp', -1)]
                    )
                    
                    # 确定设备状态和最后活跃时间
                    status = "offline"
                    last_active_str = None
                    battery_level = 0
                    
                    if latest_data and 'timestamp' in latest_data:
                        last_active_dt = datetime.fromtimestamp(latest_data['timestamp'])
                        last_active_str = last_active_dt.strftime('%Y-%m-%d %H:%M:%S')
                        if (datetime.now() - last_active_dt) < timedelta(minutes=10):
                            status = "online"
                        battery_level = latest_data.get('data', {}).get('battery', 85)
                    
                    devices_list.append({
                        'id': device.id,
                        'deviceId': device.device_id,
                        'name': device.name,
                        'deviceName': device.name,
                        'deviceLocation': device.location,
                        'type': device.type,
                        'status': status,
                        'location': device.location,
                        'lastActive': last_active_str,
                        'battery': battery_level
                    })
            
            # 返回设备列表和总数
            return jsonify({
                'code': 200,
                'msg': '查询成功',
                'data': {
                    'devices': devices_list,
                    'total': len(devices_list)
                }
            }), 200

        device = Device.query.filter_by(device_id=device_id_param).first()
        if not device:
            return jsonify({'code': 404, 'msg': '设备不存在', 'data': None}), 404

        user = User.query.filter_by(id=user_id_param).first() # 假设User ID是主键
        if not user:
            return jsonify({'code': 404, 'msg': '用户不存在', 'data': None}), 404
        
        # 检查用户设备绑定关系
        user_device_link = UserDevice.query.filter_by(user_id=user.id, device_id=device.id).first()
        if not user_device_link:
            return jsonify({'code': 403, 'msg': '用户未绑定该设备或无权限访问', 'data': None}), 403

        # 模拟数据，实际应从数据库或设备服务获取
        status = "offline"
        last_active_str = None
        battery_level = 0
        battery_status = "low"
        sensor_health = 0
        sensor_health_status = "error"
        usage_time_str = "0小时"
        usage_frequency_str = "每天0次"

        latest_data = mongodb.db.environment_data.find_one(
            {'deviceId': device_id_param},
            sort=[('timestamp', -1)]
        )

        if latest_data and 'timestamp' in latest_data:
            last_active_dt = datetime.fromtimestamp(latest_data['timestamp'])
            last_active_str = last_active_dt.strftime('%Y-%m-%d %H:%M:%S')
            if (datetime.now() - last_active_dt) < timedelta(minutes=10): # 10分钟内活跃算在线
                status = "online"
            
            # 模拟电池和传感器数据，实际应来自 latest_data
            battery_level = latest_data.get('data', {}).get('battery', 85) # 假设数据中有battery字段
            battery_status = "normal" if battery_level > 20 else "low"
            
            sensor_health = latest_data.get('data', {}).get('sensor_health', 95) # 假设数据中有sensor_health字段
            if sensor_health > 90:
                sensor_health_status = "normal"
            elif sensor_health > 70:
                sensor_health_status = "warning"
            else:
                sensor_health_status = "error"

        # 计算使用时间和频率
        start_ts = _parse_date_to_timestamp(start_date_str)
        end_ts = _parse_date_to_timestamp(end_date_str, end_of_day=True)

        query_filter = {'deviceId': device_id_param}
        if start_ts and end_ts:
            query_filter['timestamp'] = {'$gte': start_ts, '$lte': end_ts}
        elif start_ts:
            query_filter['timestamp'] = {'$gte': start_ts}
        elif end_ts:
            query_filter['timestamp'] = {'$lte': end_ts}
        
        # 如果没有时间范围，则统计所有数据
        if not start_ts and not end_ts and latest_data: # 默认统计最近24小时
            start_ts_default = int((datetime.now() - timedelta(days=1)).timestamp())
            query_filter['timestamp'] = {'$gte': start_ts_default}


        data_points_cursor = mongodb.db.environment_data.find(query_filter)
        data_points_list = list(data_points_cursor)
        num_data_points = len(data_points_list)

        if num_data_points > 0:
            # 假设每条数据代表5分钟的活跃时间，或者根据数据中的特定字段判断
            total_active_minutes = num_data_points * 5 
            usage_time_str = f"{total_active_minutes // 60}小时{total_active_minutes % 60}分钟"
            
            # 频率计算
            if start_ts and end_ts:
                duration_days = (end_ts - start_ts) / (24 * 3600)
                if duration_days >= 1:
                    usage_frequency_str = f"平均每天{num_data_points / duration_days:.1f}次"
                else: # 小于一天，显示总次数
                    usage_frequency_str = f"共{num_data_points}次"
            else: # 如果没有指定范围，可以基于总数据量或默认时间范围
                 usage_frequency_str = f"最近24小时内{num_data_points}次"


        response_data = {
            "status": status,
            "lastActive": last_active_str,
            "batteryLevel": battery_level,
            "batteryStatus": battery_status,
            "sensorHealth": sensor_health,
            "sensorHealthStatus": sensor_health_status,
            "usageTime": usage_time_str,
            "usageFrequency": usage_frequency_str
        }
        return jsonify({'code': 0, 'msg': 'success', 'data': response_data})

    except Exception as e:
        logger.error(f"获取设备状态和用户使用情况数据异常: {str(e)}")
        return jsonify({'code': 500, 'msg': f'服务器错误: {str(e)}', 'data': None}), 500

# 2. 获取设备使用情况统计
@device_bp.route('/usage', methods=['GET'])
@auth_required
def get_device_usage_statistics():
    """获取设备在指定时间范围内的使用统计数据"""
    try:
        device_id = request.args.get('deviceId')
        start_date_str = request.args.get('startDate')
        end_date_str = request.args.get('endDate')
        granularity = request.args.get('granularity', 'day')

        if not device_id or not start_date_str or not end_date_str:
            return jsonify({'code': 400, 'msg': '缺少必要参数deviceId, startDate或endDate', 'data': None}), 400

        start_ts = _parse_date_to_timestamp(start_date_str)
        end_ts = _parse_date_to_timestamp(end_date_str, end_of_day=True)

        if not start_ts or not end_ts:
            return jsonify({'code': 400, 'msg': '日期格式错误', 'data': None}), 400
        
        device = Device.query.filter_by(device_id=device_id).first()
        if not device:
            return jsonify({'code': 404, 'msg': '设备不存在', 'data': None}), 404

        # MongoDB聚合操作
        # 定义时间格式化和分组依据
        if granularity == 'hour':
            group_id_format = '%Y-%m-%d %H:00'
        elif granularity == 'day':
            group_id_format = '%Y-%m-%d'
        elif granularity == 'week':
            group_id_format = '%Y-%U' # 年份-周数 (周日为第一天)
        elif granularity == 'month':
            group_id_format = '%Y-%m'
        else:
            return jsonify({'code': 400, 'msg': '无效的时间粒度参数', 'data': None}), 400

        pipeline = [
            {'$match': {
                'deviceId': device_id,
                'timestamp': {'$gte': start_ts, '$lte': end_ts}
            }},
            {'$group': {
                '_id': {'$dateToString': {'format': group_id_format, 'date': {'$toDate': {'$multiply': ['$timestamp', 1000]}}}},
                'work_duration_points': {'$sum': 1}, # 假设每个点代表5分钟
                'power_on_count': {'$addToSet': '$sessionId'} # 假设有sessionId来区分不同的开机周期，否则模拟
            }},
            {'$sort': {'_id': 1}}
        ]
        
        results = list(mongodb.db.environment_data.aggregate(pipeline))

        categories = []
        work_hours_data = []
        power_on_data = []

        for res in results:
            categories.append(res['_id'])
            work_hours_data.append(round((res['work_duration_points'] * 5) / 60, 1)) # 转换为小时
            # 如果没有sessionId，可以简单地将每个时间段视为一次开机，或根据业务逻辑调整
            power_on_data.append(len(res['power_on_count']) if 'sessionId' in res else 1) 


        response_data = {
            "categories": categories,
            "series": [
                {"name": "工作时长(小时)", "data": work_hours_data},
                {"name": "开机次数", "data": power_on_data}
            ]
        }
        return jsonify({'code': 0, 'msg': 'success', 'data': response_data})

    except Exception as e:
        logger.error(f"获取设备使用情况统计异常: {str(e)}")
        return jsonify({'code': 500, 'msg': f'服务器错误: {str(e)}', 'data': None}), 500

# 3. 获取设备异常数据
@device_bp.route('/anomalies', methods=['GET'])
@auth_required
def get_device_anomalies_data():
    """获取设备在指定时间范围内的异常点数据"""
    try:
        device_id = request.args.get('deviceId')
        start_date_str = request.args.get('startDate')
        end_date_str = request.args.get('endDate')

        if not device_id or not start_date_str or not end_date_str:
            return jsonify({'code': 400, 'msg': '缺少必要参数deviceId, startDate或endDate', 'data': None}), 400

        start_ts = _parse_date_to_timestamp(start_date_str)
        end_ts = _parse_date_to_timestamp(end_date_str, end_of_day=True)

        if not start_ts or not end_ts:
            return jsonify({'code': 400, 'msg': '日期格式错误', 'data': None}), 400
            
        device = Device.query.filter_by(device_id=device_id).first()
        if not device:
            return jsonify({'code': 404, 'msg': '设备不存在', 'data': None}), 404
            
        data_cursor = mongodb.db.environment_data.find({
            'deviceId': device_id,
            'timestamp': {'$gte': start_ts, '$lte': end_ts}
        }).sort('timestamp', 1)
        
        timestamps_list = []
        values_list = []  # 1 for anomaly, 0 for normal
        anomalies_details_list = []

        # 示例异常阈值，实际应从配置或设备模型获取
        thresholds = {
            'pm25': {'max': 75, 'desc': 'PM2.5超标'},
            'co2': {'max': 1000, 'desc': 'CO2超标'},
            'temperature': {'min': 0, 'max': 40, 'desc': '温度异常'},
            # 添加更多参数的阈值
        }

        for item in data_cursor:
            dt_object = datetime.fromtimestamp(item['timestamp'])
            formatted_timestamp = dt_object.strftime('%Y-%m-%d %H:%M')
            timestamps_list.append(formatted_timestamp)
            
            is_anomaly_point = 0
            item_data = item.get('data', {})

            for key, thold in thresholds.items():
                value = item_data.get(key)
                if value is not None:
                    anomaly_detected_for_key = False
                    if 'max' in thold and value > thold['max']:
                        anomaly_detected_for_key = True
                    if 'min' in thold and value < thold['min']:
                        anomaly_detected_for_key = True
                    
                    if anomaly_detected_for_key:
                        is_anomaly_point = 1
                        anomalies_details_list.append({
                            "timestamp": formatted_timestamp,
                            "type": f"{key}_threshold_exceeded",
                            "description": thold['desc'] + f" (当前值: {value})"
                        })
                        break # 一旦检测到任何异常，就标记此数据点并跳出内部循环
            
            values_list.append(is_anomaly_point)

        response_data = {
            "timestamps": timestamps_list,
            "values": values_list,
            "anomalies": anomalies_details_list
        }
        return jsonify({'code': 0, 'msg': 'success', 'data': response_data})

    except Exception as e:
        logger.error(f"获取设备异常数据异常: {str(e)}")
        return jsonify({'code': 500, 'msg': f'服务器错误: {str(e)}', 'data': None}), 500

# 4. 获取设备问题告警分布数据
@device_bp.route('/alert-distribution', methods=['GET'])
@auth_required
def get_device_alert_distribution_data():
    """获取设备在指定时间范围内的各类问题告警分布"""
    try:
        device_id = request.args.get('deviceId')
        start_date_str = request.args.get('startDate')
        end_date_str = request.args.get('endDate')

        if not device_id or not start_date_str or not end_date_str:
            return jsonify({'code': 400, 'msg': '缺少必要参数deviceId, startDate或endDate', 'data': None}), 400

        start_ts = _parse_date_to_timestamp(start_date_str)
        end_ts = _parse_date_to_timestamp(end_date_str, end_of_day=True)

        if not start_ts or not end_ts:
            return jsonify({'code': 400, 'msg': '日期格式错误', 'data': None}), 400

        device = Device.query.filter_by(device_id=device_id).first()
        if not device:
            return jsonify({'code': 404, 'msg': '设备不存在', 'data': None}), 404

        # 假设告警数据存储在 mongodb.db.alerts 集合中
        # 或者通过分析 environment_data 生成
        # 此处为模拟实现，实际应查询告警数据
        pipeline = [
            {'$match': {
                'deviceId': device_id,
                'timestamp': {'$gte': start_ts, '$lte': end_ts},
                # 'is_alert': True # 假设有个字段标记是否为告警
            }},
            {'$group': {
                '_id': '$alertType', # 假设告警数据中有 alertType 字段
                'count': {'$sum': 1}
            }}
        ]
        # results = list(mongodb.db.alerts.aggregate(pipeline)) # 实际查询
        
        # 模拟返回数据，因为没有 alerts 集合和 alertType 字段
        # 你需要根据实际存储的告警数据来聚合
        mock_results = [
            {"name": "设备离线", "value": 0}, # 需要逻辑判断设备是否离线
            {"name": "低电量", "value": 0},   # 需要从数据中判断
            {"name": "传感器故障", "value": 0}, # 需要从数据中判断
            {"name": "硬件故障", "value": 0},
            {"name": "其他", "value": 0}
        ]
          # 直接从数据中统计异常，而不是调用API路由函数
        try:
            # 创建与anomalies接口相似的查询条件
            anomalies_query = {
                'deviceId': device_id,
                'timestamp': {'$gte': start_ts, '$lte': end_ts}
            }
            
            anomalies_cursor = mongodb.db.environment_data.find(anomalies_query)
            
            # 定义异常阈值
            thresholds = {
                'pm25': {'max': 75, 'desc': 'PM2.5超标'},
                'co2': {'max': 1000, 'desc': 'CO2超标'},
                'temperature': {'min': 0, 'max': 40, 'desc': '温度异常'},
            }
            
            # 统计各类异常
            for item in anomalies_cursor:
                item_data = item.get('data', {})
                
                # 检查pm25超标 - 传感器故障
                if 'pm25' in item_data and item_data['pm25'] > thresholds['pm25']['max']:
                    for result in mock_results:
                        if result["name"] == "传感器故障":
                            result["value"] += 1
                            break
                
                # 检查电池电量低
                if 'battery' in item_data and item_data['battery'] < 20:
                    for result in mock_results:
                        if result["name"] == "低电量":
                            result["value"] += 1
                            break
                            
                # 检查离线设备
                last_active = datetime.fromtimestamp(item['timestamp'])
                if (datetime.now() - last_active) > timedelta(minutes=30):
                    for result in mock_results:
                        if result["name"] == "设备离线":
                            result["value"] += 1
                            break
        except Exception as inner_e:
            logger.error(f"处理告警统计时出错: {str(inner_e)}")
            # 继续返回模拟数据，不抛出异常

        return jsonify({'code': 0, 'msg': 'success', 'data': mock_results})

    except Exception as e:
        logger.error(f"获取设备问题告警分布数据异常: {str(e)}")
        return jsonify({'code': 500, 'msg': f'服务器错误: {str(e)}', 'data': None}), 500

# 5. 获取设备维护记录
@device_bp.route('/<string:deviceId>/maintenance-records', methods=['GET'])
@auth_required
def get_device_maintenance_records(deviceId):
    """获取指定设备的维护、维修、校准等历史记录"""
    try:
        device = Device.query.filter_by(device_id=deviceId).first()
        if not device:
            return jsonify({'code': 404, 'msg': '设备不存在', 'data': None}), 404

        # 假设维护记录存储在 mongodb.db.maintenance_logs 集合
        # records_cursor = mongodb.db.maintenance_logs.find({'deviceId': deviceId}).sort('time', -1)
        # result = [
        #     {"time": r['time'], "content": r['content'], "type": r.get('type', 'info')} 
        #     for r in records_cursor
        # ]
        
        # 模拟返回数据，实际应从数据库获取
        mock_records = [
            {"time": "2025-04-15 10:30", "content": "传感器校准", "type": "primary"},
            {"time": "2025-03-20 15:45", "content": "固件升级至v2.3.1", "type": "success"}
        ]
        return jsonify({'code': 0, 'msg': 'success', 'data': mock_records})

    except Exception as e:
        logger.error(f"获取设备维护记录异常: {str(e)}")
        return jsonify({'code': 500, 'msg': f'服务器错误: {str(e)}', 'data': None}), 500

# 6. 导出设备数据
@device_bp.route('/export-data', methods=['GET'])
@auth_required
def export_device_data():
    """导出设备的历史数据，返回文件流"""
    try:
        device_id = request.args.get('deviceId')
        start_date_str = request.args.get('startDate')
        end_date_str = request.args.get('endDate')
        file_format = request.args.get('format', 'excel') # excel or csv

        if not device_id or not start_date_str or not end_date_str:
            return jsonify({'code': 400, 'msg': '缺少必要参数deviceId, startDate或endDate', 'data': None}), 400

        start_ts = _parse_date_to_timestamp(start_date_str)
        end_ts = _parse_date_to_timestamp(end_date_str, end_of_day=True)

        if not start_ts or not end_ts:
            return jsonify({'code': 400, 'msg': '日期格式错误', 'data': None}), 400
            
        device = Device.query.filter_by(device_id=device_id).first()
        if not device:
            return jsonify({'code': 404, 'msg': '设备不存在', 'data': None}), 404

        data_cursor = mongodb.db.environment_data.find({
            'deviceId': device_id,
            'timestamp': {'$gte': start_ts, '$lte': end_ts}
        }).sort('timestamp', 1)
        
        data_list = []
        for item in data_cursor:
            record = {'timestamp': datetime.fromtimestamp(item['timestamp']).strftime('%Y-%m-%d %H:%M:%S')}
            record.update(item.get('data', {}))
            data_list.append(record)

        if not data_list:
            return jsonify({'code': 404, 'msg': '指定时间范围内无数据可导出', 'data': None}), 404

        df = pd.DataFrame(data_list)
        
        output = io.BytesIO()
        filename = f"{device_id}_data_{start_date_str}_to_{end_date_str}"

        if file_format.lower() == 'excel':
            df.to_excel(output, index=False, sheet_name='DeviceData')
            mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            filename += ".xlsx"
        elif file_format.lower() == 'csv':
            df.to_csv(output, index=False, encoding='utf-8-sig') # utf-8-sig for Excel compatibility
            mimetype = 'text/csv'
            filename += ".csv"
        else:
            return jsonify({'code': 400, 'msg': '不支持的文件格式', 'data': None}), 400
        
        output.seek(0)
        return send_file(output, mimetype=mimetype, download_name=filename, as_attachment=True)

    except Exception as e:
        logger.error(f"导出设备数据异常: {str(e)}")
        return jsonify({'code': 500, 'msg': f'服务器错误: {str(e)}', 'data': None}), 500

# 7. 获取设备历史记录（分页）
@device_bp.route('/history', methods=['GET'])
@auth_required
def get_device_history_paginated():
    """获取设备的历史数据记录（分页）"""
    try:
        device_id = request.args.get('deviceId')
        start_date_str = request.args.get('startDate')
        end_date_str = request.args.get('endDate')
        try:
            page = int(request.args.get('page', 1))
            page_size = int(request.args.get('pageSize', 10))
        except ValueError:
            return jsonify({'code': 400, 'msg': 'page和pageSize参数必须是整数', 'data': None}), 400

        if not device_id:
            return jsonify({'code': 400, 'msg': '缺少必要参数deviceId', 'data': None}), 400
        
        device = Device.query.filter_by(device_id=device_id).first()
        if not device:
            return jsonify({'code': 404, 'msg': '设备不存在', 'data': None}), 404

        query_filter = {'deviceId': device_id}
        start_ts = _parse_date_to_timestamp(start_date_str)
        end_ts = _parse_date_to_timestamp(end_date_str, end_of_day=True)

        if start_ts and end_ts:
            query_filter['timestamp'] = {'$gte': start_ts, '$lte': end_ts}
        elif start_ts:
            query_filter['timestamp'] = {'$gte': start_ts}
        elif end_ts:
            query_filter['timestamp'] = {'$lte': end_ts}

        total_items = mongodb.db.environment_data.count_documents(query_filter)
        
        data_cursor = mongodb.db.environment_data.find(query_filter)\
            .sort('timestamp', -1)\
            .skip((page - 1) * page_size)\
            .limit(page_size)
            
        items_list = []
        for item in data_cursor:
            # 根据API文档示例构造返回的item结构
            # 这里的 status, batteryLevel, sensorHealth, workMode 需要从 item['data'] 中获取或模拟
            item_data = item.get('data', {})
            items_list.append({
                "timestamp": datetime.fromtimestamp(item['timestamp']).strftime('%Y-%m-%d %H:%M:%S'),
                "status": item_data.get('device_status', 'online'), # 假设有 device_status 字段
                "batteryLevel": item_data.get('battery', 85),
                "sensorHealth": item_data.get('sensor_health', 95),
                "workMode": item_data.get('work_mode', '自动'),
                "raw_data": item_data # 可以选择包含原始数据点
            })
        
        response_data = {
            "items": items_list,
            "total": total_items,
            "page": page,
            "pageSize": page_size,
            "totalPages": (total_items + page_size - 1) // page_size if page_size > 0 else 0
        }
        return jsonify({'code': 0, 'msg': 'success', 'data': response_data})

    except Exception as e:
        logger.error(f"获取设备历史记录异常: {str(e)}")
        return jsonify({'code': 500, 'msg': f'服务器错误: {str(e)}', 'data': None}), 500

# 10. 分析设备数据
@device_bp.route('/analyze', methods=['POST'])
@auth_required
# @require_json # 如果严格要求请求体是JSON
def analyze_device_data():
    """对设备数据进行分析，返回分析结果"""
    try:
        # 假设请求体是JSON
        if not request.is_json:
            return jsonify({'code': 400, 'msg': '请求体必须是JSON格式', 'data': None}), 400
            
        data = request.get_json()
        device_id = data.get('deviceId')
        start_date_str = data.get('startDate')
        end_date_str = data.get('endDate')
        # 其他分析参数: analysis_type = data.get('analysisType')

        if not device_id or not start_date_str or not end_date_str:
            return jsonify({'code': 400, 'msg': '缺少必要参数deviceId, startDate或endDate', 'data': None}), 400

        start_ts = _parse_date_to_timestamp(start_date_str)
        end_ts = _parse_date_to_timestamp(end_date_str, end_of_day=True)

        if not start_ts or not end_ts:
            return jsonify({'code': 400, 'msg': '日期格式错误', 'data': None}), 400
            
        device = Device.query.filter_by(device_id=device_id).first()
        if not device:
            return jsonify({'code': 404, 'msg': '设备不存在', 'data': None}), 404

        # 此处为分析逻辑的占位符
        # 实际分析可能涉及复杂计算、机器学习模型等
        # 例如，可以查询数据并计算一些统计指标
        data_cursor = mongodb.db.environment_data.find({
            'deviceId': device_id,
            'timestamp': {'$gte': start_ts, '$lte': end_ts}
        })
        count = mongodb.db.environment_data.count_documents({
            'deviceId': device_id,
            'timestamp': {'$gte': start_ts, '$lte': end_ts}
        })

        analysis_result_content = f"在指定时间范围内共找到 {count} 条数据点。"
        analysis_details = {
            "data_points_count": count,
            "time_range_seconds": end_ts - start_ts,
            "average_interval_seconds": (end_ts - start_ts) / count if count > 0 else 0
            # 可以添加更多分析细节
        }
        
        response_data = {
            "result": analysis_result_content,
            "details": analysis_details
        }
        return jsonify({'code': 0, 'msg': 'success', 'data': response_data})

    except Exception as e:
        logger.error(f"分析设备数据异常: {str(e)}")
        return jsonify({'code': 500, 'msg': f'服务器错误: {str(e)}', 'data': None}), 500

# 2. 获取设备列表 (更简单的接口，不需要设备ID参数)
@device_bp.route('/list', methods=['GET'])
@auth_required
def get_device_list():
    """获取用户的设备列表"""
    try:
        user_id = g.user_id  # 从认证装饰器中获取
        
        # 分页参数
        page = request.args.get('page', 1, type=int)
        size = request.args.get('size', 10, type=int)
        
        # 筛选参数
        device_name = request.args.get('deviceName', '')
        status_filter = request.args.get('status', '')
        
        # 查询用户
        user = User.query.filter_by(id=user_id).first()
        if not user:
            return jsonify({'code': 404, 'msg': '用户不存在', 'data': None}), 404
            
        # 查询与该用户关联的所有设备
        query = db.session.query(Device).join(
            UserDevice, UserDevice.device_id == Device.id
        ).filter(UserDevice.user_id == user.id)
        
        # 应用筛选条件
        if device_name:
            query = query.filter(Device.name.like(f'%{device_name}%'))
            
        # 计算总数
        total = query.count()
        
        # 应用分页
        devices_db = query.offset((page - 1) * size).limit(size).all()
        
        # 获取设备列表
        devices_list = []
        for device in devices_db:
            latest_data = mongodb.db.environment_data.find_one(
                {'deviceId': device.device_id},
                sort=[('timestamp', -1)]
            )
            
            # 确定设备状态和最后活跃时间
            status = "offline"
            last_active_str = None
            battery_level = 0
            
            if latest_data and 'timestamp' in latest_data:
                last_active_dt = datetime.fromtimestamp(latest_data['timestamp'])
                last_active_str = last_active_dt.strftime('%Y-%m-%d %H:%M:%S')
                if (datetime.now() - last_active_dt) < timedelta(minutes=10):
                    status = "online"
                battery_level = latest_data.get('data', {}).get('battery', 85)
                
            # 如果有状态筛选，跳过不匹配的设备
            if status_filter and status != status_filter:
                continue
            
            devices_list.append({
                'id': device.id,
                'deviceId': device.device_id,
                'name': device.name,
                'deviceName': device.name,
                'deviceLocation': device.location,
                'type': device.type,
                'status': status,
                'location': device.location,
                'lastActive': last_active_str,
                'battery': battery_level
            })
        
        # 返回设备列表和总数
        return jsonify({
            'code': 200,
            'msg': '查询成功',
            'data': {
                'devices': devices_list,
                'total': len(devices_list)  # 使用筛选后的实际数量
            }
        }), 200
            
    except Exception as e:
        logger.error(f"获取设备列表失败: {str(e)}")
        return jsonify({'code': 500, 'msg': f'服务器错误: {str(e)}', 'data': None}), 500